#include "ResourceManager.h"
#include <application.h>
#include <filesystem>
#include <glad/glad.h>
#include <stb_image.h>

namespace fs = std::filesystem;

void LoadTextureFromFile(const char* path,unsigned int &textureID,int &width,int &height,int &numberComponents,bool bFlip)
{
	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D, textureID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	if (bFlip)
		stbi_set_flip_vertically_on_load(true);
	else
		stbi_set_flip_vertically_on_load(false);

	unsigned char* data = stbi_load(path, &width, &height, &numberComponents, 0);
	if (data)
	{
		GLenum format= GL_RGB;
		if (numberComponents == 1)
			format = GL_RED;
		else if (numberComponents == 3)
			format = GL_RGB;
		else if (numberComponents == 4)
			format = GL_RGBA;

		glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
		glGenerateMipmap(GL_TEXTURE_2D);

		stbi_image_free(data);
	}
}

ResourceManager::ResourceManager()
{
	_loadTexture();
}


void ResourceManager::_loadTexture()
{
	std::string path = Application::FindHomePath() + "data/image";
	for (auto& fe : fs::directory_iterator(path))
	{
		auto& fp = fe.path();
		auto path = fp.generic_string();
		std::string nameWithoutExtension = fp.stem().generic_u8string();
		std::string name = fp.filename().generic_u8string();
		std::string ext = fp.extension().generic_u8string();
		if (ext == ".png") {
			std::shared_ptr<Texture> t = std::make_shared<Texture>(name);
			LoadTextureFromFile(path.c_str(), t->id, t->width, t->height, t->numberComponents, t->bFlip);
			AddTexture(t);
		}
	}
}

